Spring IoC 和 DI 的简单实现

源码跟踪

在这篇文章中,我将着重详细介绍 springframework(这里使用的版本是 6.2.15)的控制反转(IoC)和 依赖注入(DI)的具体实现,并带你真正手搓一个简化的 spring 容器出来。注解形式的 IoC 容器在元数据解析的实现上与 xml 形式有差异,但在容器运行整体流程上二者基本相同,这里仅以 xml 的视角为例进行说明。

测试 Demo 的构建:

1
2
3
4
5
6
<!--依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>6.2.15</version>
</dependency>

业务类:

1
2
3
4
5
@Data
public class User {
private String id;
private String name;
}
1
2
3
4
<bean id="user" class="com.demo.entity.User">
<property name="id" value="1"/>
<property name="name" value="Owlias"/>
</bean>

测试方法:

1
2
3
4
5
6
7
@Test
void test01() {
ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
User user = (User) context.getBean("user");
System.out.println(user);
System.out.println(user.getName());
}

源码跟踪时的关键断点:

Spring 6 IoC and DI Step 0 / 5
Internal Method Stack
// 准备追踪 ClassPathXmlApplicationContext 启动流程...
Class & Implementation
等待启动
点击“下一步”开始分析从 new 对象到 Bean 准备就绪的完整底层调用链。


手搓一个 Sping 容器出来

第一阶段:资源与元数据

资源加载模块 (Resource):Spring 的巧妙之处在于它不直接操作 File,而是抽象出了 Resource 接口。这样无论你的 XML 是在类路径、磁盘还是网络,容器的处理逻辑都是一样的。

Resource 接口:

1
2
3
4
5
6
7
8
9
/**
* 1::resource
*
* @author KJ
* @description 资源加载接口,所有资源加载的顶层抽象
*/
public interface Resource {
InputStream getInputStream() throws IOException;
}

ClassPathResource 实现类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* 1::resource
*
* @author KJ
* @description 类路径资源加载实现
*/
public class ClassPathResource implements Resource {

private final String path;
public ClassPathResource(String path) {
this.path = path;
}

@Override
public InputStream getInputStream() throws IOException {
// 使用当前线程的类加载器获取流
InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(path);
if (is == null) {
throw new FileNotFoundException(path + " cannot be opened because it does not exist");
}
return is;
}
}

有了资源读取能力,我们需要定义一个类来存储解析出来的 XML 信息。这就是 BeanDefinition:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/**
* 2::definition
*
* @author KJ
* @description Bean画像的定义:Bean 的定义信息(这里简单化处理,只包含基本的类名和属性集合)
*/
public class BeanDefinition {

@Getter
private String beanClassName;
@Getter
private List<PropertyValue> propertyValues = new ArrayList<>();

public BeanDefinition(String beanClassName) {
this.beanClassName = beanClassName;
}

public void addPropertyValue(PropertyValue pv) {
this.propertyValues.add(pv);
}
}

“画像” 的属性单元 PropertyValue:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
* 2::definition
*
* @author KJ
* @description 属性单元:对应 XML 中的 <property name="..." value="..."/>
*/
public class PropertyValue {

private final String name;
private final Object value;

public PropertyValue(String name, Object value) {
this.name = name;
this.value = value;
}

public String getName() {
return name;
}

public Object getValue() {
return value;
}
}

有了Bean的 “画像”,我们需要一个能存放 “画像” 的地方。Spring 设计了 BeanDefinitionRegistry 接口,让工厂具备注册画像的能力。

1
2
3
4
5
6
7
8
9
/**
* 3::registry
*
* @author KJ
* @description 存放 BeanDefinition 的注册表接口
*/
public interface BeanDefinitionRegistry {
void registerBeanDefinition(String beanName, BeanDefinition beanDefinition);
}

第一阶段的灵魂组件 BeanDefinitionReader。在 Spring 中,它的职责是拿着刚刚我们写的 Resource,通过 DOM 解析 XML 标签,把 id 和 class 提取出来,封装成 BeanDefinition,最后塞进工厂的 beanDefinitionMap 里。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.InputStream;

/**
* 3::registry
*
* @author KJ
* @description 负责读取 XML 并注册 BeanDefinition
*/
public class XmlBeanDefinitionReader {

private final BeanDefinitionRegistry registry;
public XmlBeanDefinitionReader(BeanDefinitionRegistry registry) {
this.registry = registry;
}

public void loadBeanDefinitions(Resource resource) throws Exception {
try (InputStream inputStream = resource.getInputStream()) {
doLoadBeanDefinitions(inputStream);
}
}

protected void doLoadBeanDefinitions(InputStream inputStream) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(inputStream);
Element root = doc.getDocumentElement();
NodeList nodes = root.getChildNodes();

for (int i = 0; i < nodes.getLength(); i++) {
if (!(nodes.item(i) instanceof Element)) continue;
Element ele = (Element) nodes.item(i);
if (!"bean".equals(ele.getNodeName())) continue;

// 1. 提取 id 和 class
String id = ele.getAttribute("id");
String className = ele.getAttribute("class");

// 2. 创建画像
BeanDefinition beanDefinition = new BeanDefinition(className);

// 3. 提取属性注入 <property name="" value=""/>
NodeList propNodes = ele.getElementsByTagName("property");
for (int j = 0; j < propNodes.getLength(); j++) {
Element propEle = (Element) propNodes.item(j);
String name = propEle.getAttribute("name");
String value = propEle.getAttribute("value");
beanDefinition.addPropertyValue(new PropertyValue(name, value));
}

// 4. 注册到工厂
registry.registerBeanDefinition(id, beanDefinition);
}
}
}

最后实现一个最简单的工厂 (BeanFactory):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
* 4::factory
*
* @author KJ
* @description 实现一个最简单的 BeanFactory 工厂,它需要实现 BeanDefinitionRegistry 接口,这样它才能被 Reader 填充。
*/
public class DefaultListableBeanFactory implements BeanDefinitionRegistry {

// 这就是所有bean组件注册 “画像” 存储的地方
private final Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>();

@Override
public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition) {
beanDefinitionMap.put(beanName, beanDefinition);
}

public BeanDefinition getBeanDefinition(String beanName) {
return beanDefinitionMap.get(beanName);
}
}

现在,我们可以真正通过读取 XML 来生成画像了!来,简单测试一下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@Test
public void test01() throws Exception {
// 1. 创建工厂 (注册表)
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();

// 2. 创建读取器并绑定工厂
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(factory);

// 3. 加载资源并解析
Resource resource = new ClassPathResource("bean.xml");
reader.loadBeanDefinitions(resource);

// 4. 验证画像是否存入 Map
BeanDefinition bd = factory.getBeanDefinition("user");
System.out.println("成功加载 Bean: " + bd.getBeanClassName());
PropertyValue pv0 = bd.getPropertyValues().get(0);
System.out.println("属性注入检测: " + pv0.getName() + " = " + pv0.getValue());
PropertyValue pv1 = bd.getPropertyValues().get(1);
System.out.println("属性注入检测: " + pv1.getName() + " = " + pv1.getValue());
}

测试结果:

1
2
3
成功加载 Bean: com.demo.entity.User
属性注入检测: id = 1
属性注入检测: name = Owlias


第二阶段:实现控制反转

在第一阶段,我们已经把 “设计图纸”(BeanDefinition)塞进了 beanDefinitionMap。现在我们要打造那台根据图纸生产零件的 “机器”——getBean 流程。

按照 Spring 的设计,我们要通过模板模式来组织代码:

  • BeanFactory: 顶层接口,定义 getBean 协议。
  • AbstractBeanFactory: 抽象类,处理单例缓存逻辑(一级缓存)。
  • AbstractAutowireCapableBeanFactory: 负责具体的实例化(反射 new 对象)和初始化。
  • DefaultListableBeanFactory:落地实现类,它继承了上面的所有生产能力,并且实现了 BeanDefinitionRegistry。

下面我们来具体实现这一阶段的主要逻辑:

BeanFactory:

1
2
3
4
5
6
7
8
9
/**
* 4::factory
*
* @author KJ
* @description 顶层工厂接口
*/
public interface BeanFactory {
Object getBean(String name) throws Exception;
}

AbstractBeanFactory:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/**
* 4::factory
*
* @author KJ
* @description 抽象bean工厂:在此我们实现单例控制
*/
public abstract class AbstractBeanFactory implements BeanFactory {

/** 一级缓存:保存训练好的完整单例对象 */
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);

@Override
public Object getBean(String name) throws Exception {
Object bean = singletonObjects.get(name);
if (bean != null) {
return bean;
}

// 获取该 Bean 的画像
BeanDefinition beanDefinition = getBeanDefinition(name);
if (beanDefinition == null) {
throw new Exception("No bean named " + name + " is defined");
}
// 如果单例池没有,就去创建一个
return createBean(name, beanDefinition);
}

/**
* 方便子类将创建好的单例放入池中
*/
protected void addSingleton(String beanName, Object singletonObject) {
singletonObjects.put(beanName, singletonObject);
}

protected abstract BeanDefinition getBeanDefinition(String beanName);
protected abstract Object createBean(String beanName, BeanDefinition beanDefinition) throws Exception;
}

AbstractAutowireCapableBeanFactory:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/**
* 4::factory
*
* @author KJ
* @description 抽象bean工厂:在此实现通过反射创建对象
*/
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory {

@Override
protected Object createBean(String beanName, BeanDefinition beanDefinition) throws Exception {
Object bean;
try {
// 1. 实例化阶段:反射创建空对象
bean = createBeanInstance(beanDefinition);

// 2. 填充属性阶段 (这是第三阶段的内容,我们先留个坑)
applyPropertyValues(beanName, bean, beanDefinition);
} catch (Exception e) {
throw new RuntimeException("Instantiation of bean failed", e);
}
// 放入单例池
addSingleton(beanName, bean);
return bean;
}

protected Object createBeanInstance(BeanDefinition beanDefinition) throws Exception {
// 简单实现:通过全类名获取 Class 对象,再通过默认构造函数反射
Class<?> beanClass = Class.forName(beanDefinition.getBeanClassName());
return beanClass.getDeclaredConstructor().newInstance();
}

protected void applyPropertyValues(String beanName, Object bean, BeanDefinition beanDefinition) {
// TODO: 遍历 PropertyValues 进行 Setter 注入
}
}

DefaultListableBeanFactory:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
* 4::factory
*
* @author KJ
* @description 具体干活的bean工厂:它继承了工厂的所有生产能力,并且实现了第一阶段写的 BeanDefinitionRegistry。
*/
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements BeanDefinitionRegistry {

// 这就是所有bean组件注册 “画像” 存储的地方
private final Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>();

@Override
public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition) {
beanDefinitionMap.put(beanName, beanDefinition);
}

public BeanDefinition getBeanDefinition(String beanName) {
return beanDefinitionMap.get(beanName);
}
}

通过第二阶段,现在我们就能够搓出一个由工厂创建的真正的 user 了!来,测试:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Test
public void test03() throws Exception {
// 1. 创建工厂 (注册表)
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();

// 2. 创建读取器并绑定工厂
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(factory);

// 3. 加载资源并解析
Resource resource = new ClassPathResource("bean.xml");
reader.loadBeanDefinitions(resource);

// 4. 核心:调用 getBean (控制反转),此时 User 对象的创建权完全交给了 factory
User user = (User) factory.getBean("user");
System.out.println(user);
System.out.println(user.getClass() + "@" + Integer.toHexString(System.identityHashCode(user)));
user.sayHello();
}

测试结果:

1
2
3
User(id=null, name=null)
class com.demo.entity.User@6dc17b83
hello world


第三阶段:实现依赖注入

在第二阶段,我们已经通过反射 new 出了对象,但它只是一个 “空壳”。现在我们要实现 applyPropertyValues 方法,利用反射把配置中的属性值强行灌输给这个空壳,让它变成一个具备业务数据的 “完全体”。

在 Spring 源码中,这个过程是由 BeanWrapper 来配合完成的,但在我们的简易版实现中,我们将通过简单的反射对 Setter 方法进行调用。

现在,我们就实现之前 AbstractAutowireCapableBeanFactory#applyPropertyValues 的坑位:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory {

// ...

protected void applyPropertyValues(String beanName, Object bean, BeanDefinition beanDefinition) throws Exception {
try {
for (PropertyValue pv : beanDefinition.getPropertyValues()) {
String name = pv.getName();
Object value = pv.getValue();

// 核心技巧:根据属性名拼接出 setXxx 方法名
// 例如 name -> setName
String setterMethodName = "set" + name.substring(0, 1).toUpperCase() + name.substring(1);

// 获取该对象的 Class
Class<?> clazz = bean.getClass();

// 简单实现:为了演示,假设我们只支持 String 类型的属性注入
// 在真实的 Spring 中,这里会涉及极其复杂的类型转换 (TypeConverter)
Method method = clazz.getDeclaredMethod(setterMethodName, value.getClass());

// 消除访问限制检查 (确保私有 setter 也能调用)
method.setAccessible(true);

// 反射调用:targetBean.setName("Owlias")
method.invoke(bean, value);
}
} catch (Exception e) {
throw new Exception("Error setting property values for bean: " + beanName, e);
}
}
}

现在再来运行第二阶段的测试单元:

1
2
3
User(id=1, name=Owlias)
class com.demo.entity.User@1283bb96
hello world

DI 注入,大功告成!


让使用更优雅

你可能注意到咱们的测试单元调用似乎很繁琐,不像spring那样优雅,我们现在就来写一个精简版的 ApplicationContext,让它实现 “一行代码启动容器并自动注入” 的壮举!

在 Spring 源码设计中,BeanFactory 是底层容器,面向 Spring 框架本身;而 ApplicationContext 是高层容器,面向的是开发者。ApplicationContext 的核心作用是:把 Resource 加载、BeanDefinition 解析、BeanFactory 注册这几项琐碎的工作包装起来,让你实现 “一行代码启动 Spring 容器”。下面我将遵循 Spring 6 的继承体系,来实现一个最经典的 ClassPathXmlApplicationContext。

顶层接口 ApplicationContext:

1
2
3
4
5
6
7
/**
* 5::context
*
* @author KJ
* @description 面向开发者的 ApplicationContext
*/
public interface ApplicationContext extends BeanFactory {}

抽象基类 AbstractApplicationContext:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
* 5::context
*
* @author KJ
* @description 抽象基类:这里实现了 Spring 源码中最著名的 refresh() 方法,它定义了容器启动的完整标准流程。
*/
public abstract class AbstractApplicationContext implements ApplicationContext {
protected DefaultListableBeanFactory beanFactory;

@Override
public Object getBean(String name) throws Exception {
return beanFactory.getBean(name);
}

/**
* Spring 的灵魂方法:刷新容器
*/
public void refresh() throws Exception {
// 1. 创建 BeanFactory。spring 参考 {@link AbstractApplicationContext#obtainFreshBeanFactory}
refreshBeanFactory();

// 2. 预实例化单例对象(让单例在容器启动时就创建好,而不是延迟到 getBean)
// 这一步在完整 Spring 中很复杂,我们简化为直接启动流程
}

protected abstract void refreshBeanFactory() throws Exception;
}

真正干活的 XML 实现类 ClassPathXmlApplicationContext:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
* 5::context
*
* @author KJ
* @description 这是我们最终暴露给用户使用的 ApplicationContext,负责将 Resource、Reader 和 BeanFactory 揉在一起。
*/
public class ClassPathXmlApplicationContext extends AbstractApplicationContext {

private String configLocation;
public ClassPathXmlApplicationContext(String configLocation) throws Exception {
this.configLocation = configLocation;
// 核心:启动即刷新
super.refresh();
}

@Override
protected void refreshBeanFactory() throws Exception {
// 1. 构造底层工厂
DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();

// 2. 构造解析器并绑定工厂
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(beanFactory);

// 3. 加载并解析配置文件
reader.loadBeanDefinitions(new ClassPathResource(configLocation));

// 4. 将成品工厂赋值给上下文
this.beanFactory = beanFactory;
}
}

好,现在再来看我们的测试单元,是不是看起来有点像真正的 spring 容器了呢:

1
2
3
4
5
6
7
8
9
10
11
@Test
public void testMyApplicationContext() throws Exception {
// 【一行代码启动】 内部自动执行了:定位 -> 解析 -> 注册画像 -> 实例化准备
ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");

// 【获取 Bean】 触发实例化与依赖注入
User user = (User) context.getBean("user");

// 【执行业务】
user.sayHello();
}


核心 context.refresh 方法

以上我们模拟了 AbstractApplicationContext 是怎样通过 refresh 这个 模版方法 简化容器的使用的。事实上 spring 的 AbstractApplicationContext#refresh 就是这么干的!可以说这个 “refresh” 是 spring 容器的核心中的核心!我们来看 spring 容器的这个 refresh 模版方法中都干了些什么:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
package org.springframework.context.support;

public abstract class AbstractApplicationContext extends DefaultResourceLoader implements ConfigurableApplicationContext {
// ...

protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
this.refreshBeanFactory(); ////// 这就是我们上面模拟出的 DefaultListableBeanFactory!
return this.getBeanFactory();
}

public void refresh() throws BeansException, IllegalStateException {

/**
* 第 I 阶段:容器启动的防并发与指标监控准备
*
* startupShutdownLock.lock():加锁。防止在容器正在 refresh(刷新)的过程中,有别的线程并发地调用 close() 或再次 refresh,造成容器状态紊乱。
* startupShutdownThread:记录当前正在执行刷新的线程,用于后续的生命周期诊断。
* applicationStartup.start(...):Spring 5.3 引入的性能监控指标埋点,用来记录各个启动步骤耗时,方便做应用启动调优。
*/
this.startupShutdownLock.lock();
try {
this.startupShutdownThread = Thread.currentThread();
StartupStep contextRefresh = this.applicationStartup.start("spring.context.refresh");

/**
* 第 II 阶段:环境准备与 BeanFactory 诞生 - “通电、对时、搬图纸”
*
* prepareRefresh()(准备刷新):
* 设置容器的启动时间戳、激活状态标志,校验并预处理一些必须的属性(比如检查 Environment 环境变量中的关键配置)。
*
* obtainFreshBeanFactory()(获取崭新的 BeanFactory):
* 销毁旧的 BeanFactory(如果存在),并创建/初始化一个新的 DefaultListableBeanFactory。
* 加载 BeanDefinition:在这里,Spring 开始把配置文件、XML、或者注解中的类定义(Bean 的元数据)加载到内存中。
*
* prepareBeanFactory(beanFactory)(配置 BeanFactory 的基本属性):
* 给 BeanFactory 注入一些基础环境:配置类加载器(ClassLoader)、表达式解析器(SpEL)。
* 注册几个关键的后置处理器:ApplicationContextAwareProcessor(让实现了 XxxAware 接口的 Bean 能拿到容器上下文)。
* 忽略自动装配:告诉 Spring 忽略 EnvironmentAware 等接口的自动注入(改由 Aware 处理器单独处理)。
*
* postProcessBeanFactory(beanFactory)(子类自定义修改 BeanFactory):
* 这是一个钩子方法(Hook),留给子类(如 Web 容器)在 BeanFactory 标准化之后,做进一步的微调或添加特定组件。
*/
this.prepareRefresh();
ConfigurableListableBeanFactory beanFactory = this.obtainFreshBeanFactory(); //
this.prepareBeanFactory(beanFactory);
try {
this.postProcessBeanFactory(beanFactory);

/**
* 第 III 阶段:核心扫描与后置处理器注册(最关键的 “大脑风暴” 阶段)
*
* invokeBeanFactoryPostProcessors(beanFactory)(执行 BeanFactory后置处理器):
* 这里会触发执行 ConfigurationClassPostProcessor。它负责扫描你写的 @ComponentScan 路径,解析 @Import,把所有的 @Component、@Service、@Bean 统统转化成内存中的 BeanDefinition。
* 同时它还会执行各种 BeanDefinitionRegistryPostProcessor,允许开发者在 Bean 实例化之前动态往容器里注册或修改 Bean 定义。
*
* registerBeanPostProcessors(beanFactory)(注册 BeanPostProcessor):
* 扫描并注册所有实现了 BeanPostProcessor 接口的类(比如负责 AOP 代理的 AnnotationAwareAspectJAutoProxyCreator、负责 @PostConstruct 的处理器)。
* 注意:这里只是把它们注册进工厂,此时它们并没有开始工作,而是排好队等待后续被调用。
*/
StartupStep beanPostProcess = this.applicationStartup.start("spring.context.beans.post-process");
this.invokeBeanFactoryPostProcessors(beanFactory);
this.registerBeanPostProcessors(beanFactory);
beanPostProcess.end();

/**
* 第 IV 阶段:国际化、事件广播器与子类扩展(Web 容器点火点!)
*
* initMessageSource()(初始化国际化组件):
* 为 Spring 容器提供国际化支持(如多语言错误提示、消息模板解析)。
*
* initApplicationEventMulticaster()(初始化事件广播器):
* 创建 ApplicationEventMulticaster(事件发布与订阅的底层引擎)。
*
* onRefresh()(子类定制刷新钩子 —— 极其重要):
* 在标准的 ClassPathXmlApplicationContext 中,这个方法是个空方法。
* 但在 Spring Boot 的 Web 容器中(如 ServletWebServerApplicationContext),这里就是点火启动嵌入式 Tomcat(或者 Jetty / Undertow)的地方!
*
* registerListeners()(注册应用监听器):
* 把所有实现了 ApplicationListener 接口的 Bean 找出来,注册到事件广播器中。
*/
this.initMessageSource();
this.initApplicationEventMulticaster();
this.onRefresh();
this.registerListeners();

/**
* 第 V 阶段:终极杀招 —— 初始化所有单例 Bean(生命周期高潮)
*
* finishBeanFactoryInitialization(beanFactory)(初始化所有剩余的单例 Bean):
* Spring 最核心、最庞大的逻辑全在这里面!它会遍历所有 Non-lazy 的单例 Bean Definition:
* a.调用构造函数实例化(Instantiation)。
* b.进行属性填充(Populate Bean)(处理 @Autowired 依赖注入)。
* c.执行 Aware 接口回调。
* d.执行 BeanPostProcessor 的前置处理(如 @PostConstruct)。
* e.执行自定义初始化方法(init-method)。
* f.执行 BeanPostProcessor 的后置处理(在这里通过AOP代理把原始对象包装成代理对象)。
* 当这一步走完,容器里所有的业务 Bean 全部变成了“成品”,安静地躺在一级缓存(singletonObjects)里。
*
* finishRefresh()(完成刷新收尾工作):
* 初始化生命周期处理器(LifecycleProcessor),并调用实现了 Lifecycle 接口的 Bean 的 start() 方法。
* 发布 ContextRefreshedEvent 事件(通知整个系统:Spring 容器已经彻底刷新完毕,随时可以接客了!)。
* 清除缓存中的启动元数据。
*/
this.finishBeanFactoryInitialization(beanFactory);
this.finishRefresh();
} catch (Error | RuntimeException var12) {
if (this.logger.isWarnEnabled()) {
this.logger.warn("Exception encountered during context initialization - cancelling refresh attempt: " + String.valueOf(var12));
}

/**
* 第 VI 阶段:异常处理与收尾清理
*
* 调用 destroyBeans():把刚才已经创建好的半成品 Bean 全部销毁,释放内存。
* 调用 cancelRefresh():将容器的激活状态标记置为 false,宣布启动失败。
* 抛出异常,应用崩溃退出。
*/
this.destroyBeans();
this.cancelRefresh(var12);
throw var12;
} finally {
contextRefresh.end();
}
} finally {

/*
* 第 VII 阶段:finally 块
*
* 无论成功还是失败,必须关闭性能监控埋点,并释放 startupShutdownLock 锁,保证线程安全。
*/
this.startupShutdownThread = null;
this.startupShutdownLock.unlock();
}
}

// ...
}

其中,作为 context 的实现之一的 ClassPathXmlApplicationContext:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class ClassPathXmlApplicationContext extends AbstractXmlApplicationContext {
// ...

public ClassPathXmlApplicationContext(String configLocation) throws BeansException {
this(new String[]{configLocation}, true, (ApplicationContext)null);
}

public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh) throws BeansException {
this(configLocations, refresh, (ApplicationContext)null);
}

public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, @Nullable ApplicationContext parent) throws BeansException {
super(parent);
this.setConfigLocations(configLocations);
if (refresh) {
this.refresh();
}
}

// ...
}

构造的时候 refresh 完全可以传 false,这是 Spring 留给高级开发者和复杂框架集成的一个极其关键的 “黄金干预窗口”。比如在 XML 或注解扫描加载 Bean 之前,你可能想动态往容器里塞一些自己写的 BeanFactoryPostProcessor。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"beans.xml"}, false);

// 干预一:在刷新前,手动往容器注册一个自定义的后置处理器!
context.addBeanFactoryPostProcessor(new MyCustomBeanFactoryPostProcessor());

// 干预二:动态设置激活的 Profile
context.getEnvironment().setActiveProfiles("production");

// 干预三:在大型企业级应用或高级框架(如 Spring MVC 的双亲容器模型)中,经常需要把一个容器设为另一个容器的“父亲”。
// 你需要先创建好父容器并 refresh()。然后创建子容器,并在子容器调用 refresh() 之前,通过 child.setParent(parentContext) 把父子关系绑定好。
// 如果子容器在构造函数里自动 refresh 了,再绑定父容器就会引发线程安全或状态不一致的问题。

// 一切准备就绪,手动点火!
context.refresh();